function setup() {
    createCanvas(400, 400);
    frameRate(10); // 设置适中的速度
    snake = new Snake();
    foodLocation();
}

function draw() {
    background(220);
    snake.update();
    snake.show();
    if (snake.eat(food)) {
        foodLocation();
    }
    fill(255, 0, 0);
    rect(food.x, food.y, 10, 10);
}

function foodLocation() {
    let cols = floor(width / 10);
    let rows = floor(height / 10);
    food = createVector(floor(random(cols)), floor(random(rows)));
    food.mult(10);
}

class Snake {
    constructor() {
        this.body = [];
        this.body[0] = createVector(floor(width / 10 / 2) * 10, floor(height / 10 / 2) * 10);
        this.xdir = 0;
        this.ydir = 0;
        this.len = 0;
    }

    setDir(x, y) {
        this.xdir = x;
        this.ydir = y;
    }

    update() {
        let head = this.body[this.body.length - 1].copy();
        this.body.shift();
        head.x += this.xdir * 10;
        head.y += this.ydir * 10;
        this.body.push(head);
    }

    show() {
        fill(0, 255, 0); // 蛇的颜色为绿色
        for (let i = 0; i < this.body.length; i++) {
            rect(this.body[i].x, this.body[i].y, 10, 10);
        }
    }

    eat(pos) {
        let head = this.body[this.body.length - 1];
        if (head.x === pos.x && head.y === pos.y) {
            this.len++;
            this.body.push(createVector(0, 0));
            return true;
        }
        return false;
    }
}

function keyPressed() {
    if (keyCode === UP_ARROW) {
        snake.setDir(0, -1);
    } else if (keyCode === DOWN_ARROW) {
        snake.setDir(0, 1);
    } else if (keyCode === RIGHT_ARROW) {
        snake.setDir(1, 0);
    } else if (keyCode === LEFT_ARROW) {
        snake.setDir(-1, 0);
    }
}